package com.zhongying.jf.util.dislock;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import com.sys.midware.logger.Logger;
import com.sys.midware.logger.LoggerFactory;
import com.zhongying.jf.util.redis.RedisUtils;

@Component
public class DLockKeyUtil {
    private static final Logger logger = LoggerFactory.getLogger(DLockKeyUtil.class);

    /**
     * 应用启动时删除所有分布式锁 cleanDlockKey <br/>
     * void <br/>
     */
    @PostConstruct
    public void cleanDlockKeyOnStartUp() {
        logger.info("begin to clean dlock key!");
        try {
            Set<String> keys = new HashSet<>();
            Set<String> keys1 = RedisUtils.getClient().keys("DLOCK*");
            if (keys1 != null && !keys1.isEmpty()) {
                logger.info("keys of DLOCK* is:" + keys1);
                keys.addAll(keys1);
            }
            Set<String> keys2 = RedisUtils.getClient().keys("dlock*");

            if (keys2 != null && !keys2.isEmpty()) {
                logger.info("keys of dlock* is:" + keys1);
                keys.addAll(keys2);
            }
            logger.info("bengin to del dlock keys,all keys=" + keys);
            for (String key : keys) {
                RedisUtils.del(key);
            }
            logger.info("end to del dlock keys");
        } catch (Exception e) {
            logger.error("clean dlock key error!", e);
        }
    }
}
